package com.youyoulong.framework.util.service.impl;

import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.youyoulong.framework.util.SpringContextUtil;
import com.youyoulong.framework.util.dao.mapper.FrameDataInterfaceExecuteMapper;
import com.youyoulong.framework.util.service.IFrameDataInterfaceService;

/**
 * 执行SQL数据的服务类
 * 
 * @author you_lan_yan
 */
@Service("util.SQL.FrameDataInterfaceService")
public class FrameDataInterfaceSQLService implements IFrameDataInterfaceService {

	private final String mapperName = "util.[数据库类型].[数据源名称].FrameDataInterfaceExecuteMapper";
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Object execute(Map params) throws Exception {
		Map result = new LinkedHashMap();
		Map _targetDataInterfaceMap = (Map)params.get(_targetDataInterface);
		if(_targetDataInterface!=null){
			String serviceName = null;
			if(_targetDataInterfaceMap.get("dataDaoName")==null||_targetDataInterfaceMap.get("dataDaoName").toString().trim().isEmpty()){
				serviceName = mapperName.replace("[数据库类型]",_targetDataInterfaceMap.get("databaseType").toString());
				serviceName = serviceName.replace("[数据源名称]", _targetDataInterfaceMap.get("dataSource").toString());
			}else{
				serviceName = _targetDataInterfaceMap.get("dataDaoName").toString().trim();
			}
			FrameDataInterfaceExecuteMapper executeMapper = (FrameDataInterfaceExecuteMapper)SpringContextUtil.getBean(serviceName);
			
//			Map queryParams = (Map)params.get(FrameDataInterfaceMainService._queryParams);
			
			
			if(params.get(_pageKey)!=null){
				Map pageVo = new LinkedHashMap();
				params.put(_pageVoKey, pageVo);
				int page = Integer.parseInt(params.get(_pageKey).toString());
				int pageSize = params.get(_pageSizeKey)==null?10:Integer.parseInt(params.get(_pageSizeKey).toString());
				pageVo.put("start", (page-1)*pageSize);
				pageVo.put("end", page*pageSize);
				params.put(_pageSizeKey, pageSize);
				Integer totalCount = executeMapper.executeDataInterfaceCount(params);
				if(totalCount.intValue()>0){
					int totalPage = Double.valueOf(Math.ceil(totalCount.intValue()*1.0/pageSize)).intValue() ;
					pageVo.put(_totalCountKey, totalCount);
					pageVo.put(_pageSizeKey, pageSize);
					pageVo.put(_pageKey, page);
					pageVo.put(_totalPageKey, totalPage);
					
					result.put(_statusKey, IFrameDataInterfaceService._successCode);
					result.put(_dataKey, executeMapper.executeDataInterface(params));
					result.put(_pageVoKey, pageVo);
				}else{
					result.put(_statusKey, IFrameDataInterfaceService._nodataCode);
				}
				
			}else{
				result.put(_dataKey, executeMapper.executeDataInterface(params));
			}
		}else{
			
		}
		
		
		return result;
	}
}
